﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeRepositoryConsole.Concurrency
{
    /// <summary>
    /// 7 ways to start a Task in .NET C#
    /// <see cref="https://dotnetcodr.com/2014/01/01/5-ways-to-start-a-task-in-net-c/"/>
    /// </summary>
    class StartTask
    {
        public void StartATask()
        {
            // 1.
            Task.Factory.StartNew(() => { Console.WriteLine("Hello Task libary!"); });

            // 2.using action
            Task task = new Task(new Action(PrintMessage));
            task.Start();

            // 3.using delegate
            Task task3 = new Task(delegate { PrintMessage(); });
            task3.Start();

            // 4.lambda and named method
            Task task4 = new Task(() => PrintMessage());
            task4.Start();

            // 5.lambda and anonymous method
            Task task5 = new Task(() => { PrintMessage(); });
            task5.Start();

            // 6.Task.Run in .NET4.5
            Task.Run(() => PrintMessage());            
        }

        private void PrintMessage()
        {
            Console.WriteLine("Hello Task library");
        }

        /// <summary>
        /// 7.using Task.FromResult in .NET4.5 to return a result from a Task
        /// </summary>
        /// <returns></returns>
        public async Task DoWork()
        {
            int res = await Task.FromResult<int>(GetSum(4, 5));
        }

        private int GetSum(int a,int b)
        {
            return a + b;
        }
    }
}
